package ex2.employee;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

public class CManager extends CEmployee implements IEmployee  {

	private Collection<String> _subordinates;
	
	
	public CManager(String record, IEmployeeHandler employeeHandler) throws IllegalArgumentException{
		super(record, employeeHandler);
		this._subordinates = new ArrayList<String>();
		
		
		if(this._extraData != null){
			String tExtraData = this._extraData.trim();
			String tRecordToAdd = this._parser(tExtraData);
			if (tRecordToAdd.equals(this.getUsername())) 
				throw new IllegalArgumentException();
			while (!tRecordToAdd.isEmpty())
			{
				this._subordinates.add(tRecordToAdd);
							
				if (tRecordToAdd.length()+1  > tExtraData.length()) break;
				
				tExtraData = (tExtraData.substring(tRecordToAdd.length()+1)).trim();
				tRecordToAdd = this._parser(tExtraData);
				
				if (tRecordToAdd.equals(this.getUsername())) 
					throw new IllegalArgumentException();
			}
		}
	}
	
	
	@Override
	public String getFirstName() {
		return super.getFirstName();
	}

	@Override
	public String getLastName() {
		return super.getLastName();
	}

	@Override
	public String getUsername() {
		return super.getUsername();
	}

	@Override
	public double calaulateTotalExpenses() {
		
		double tAnswer = super.getSalary();
		
		for(Iterator<String> iterator = this._subordinates.iterator(); iterator.hasNext();)
			
			tAnswer += this._employeeHandler.getTotalExpenses(iterator.next());
			
		return tAnswer;
	}

	public String getSubordinates(){
		String tAnswer= "";
		
		for(Iterator<String> iterator = this._subordinates.iterator(); iterator.hasNext();){
			
			tAnswer += iterator.next();
			
			if(iterator.hasNext())
				tAnswer = tAnswer.concat(", ");
		}
		return tAnswer;
	}
	

	public void deleteRedundantData(){
		
		Collection<String> tSubordinatesToRemove = new ArrayList<String>();
		for(Iterator<String> iterator = this._subordinates.iterator(); iterator.hasNext();){
			
			String tSubordinateName = iterator.next();
			
			if(this._employeeHandler.isAvailableUsername(tSubordinateName))
				tSubordinatesToRemove.add(tSubordinateName);
			
		}
		
		for(Iterator<String> iterator = tSubordinatesToRemove.iterator(); iterator.hasNext();)	
			this._subordinates.remove(iterator.next());
			
		
	}
}
